
package com.leyou.cart.Service;

import com.leyou.auth.entity.UserInfo;
import com.leyou.cart.api.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.CartSon;
import com.leyou.cart.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    static final String KEY_PREFIX = "ly:cart:uid:";
    static final Logger logger = LoggerFactory.getLogger(CartService.class);

    public void addCart(CartSon cart) {
        //获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        //Redis中的key
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        //查询是否存在
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        Boolean aBoolean = hashOps.hasKey(skuId.toString());
        if (aBoolean) {
            //已存在 更新购物车中该商品数量并保存原来的价格数据
            String json = hashOps.get(skuId.toString()).toString();
            cart = JsonUtils.parse(json, CartSon.class);
            //查询是否限制购买数量,是否超过购买限制数量
            if (cart.getLimitNum() == null || num + cart.getNum() <= cart.getLimitNum()) {
                cart.setNum(cart.getNum() + num);
            }
            cart.setOldPrice(cart.getOldPrice());
        } else {
            //不存在，新增购物车数据
            cart.setUserId(user.getId());
            Sku sku = this.goodsClient.querySkuById(skuId);
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());

            if (cart.getLimitNum() == null) {
                cart.setPrice(sku.getPrice());
            }

            cart.setTitle(sku.getTitle());
            cart.setOldPrice(sku.getPrice());
        }
        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
    }

    public List<CartSon> queryCartList() {
        //获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        //判断是否存在购物车
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        List<Object> values = hashOps.values();
        if (CollectionUtils.isEmpty(values)) {
            return null;
        }
        //查询购物车数据
        List<CartSon> carts = values.stream().map(o -> {
            CartSon cart = JsonUtils.parse(o.toString(), CartSon.class);
            //根据skuId查询sku
            Sku sku = goodsClient.querySkuById(cart.getSkuId());
            //根据spuId查询spu
            Spu spu = goodsClient.querySpuById(sku.getSpuId());
            cart.setOldPrice(sku.getPrice());
            //上下架信息
            cart.setSaleable(spu.getSaleable());
            /*if (!spu.getSaleable()) {
                cart.setPrice(0L);
            }*/
            return cart;

        }).collect(Collectors.toList());
        return carts;

    }

    public void updateNum(@RequestBody CartSon cart) {
        //获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        //获取key
        String key = KEY_PREFIX + user.getId();
        //获取redis操作
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        Long skuId = cart.getSkuId();

        Integer num = cart.getNum();

        String cartJson = hashOps.get(skuId.toString()).toString();
        cart = JsonUtils.parse(cartJson, CartSon.class);
        cart.setNum(num);
        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));

    }

    public void deleteCart(Long id) {
        UserInfo user = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        hashOps.delete(id.toString());
    }

    public Boolean mergeCarts(List<CartSon> carts) {
        if (carts == null) {
            return false;
        }
        UserInfo user = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        for (CartSon cart : carts) {
            //查询是否存在
            Long skuId = cart.getSkuId();
            Integer num = cart.getNum();
            Boolean aBoolean = hashOps.hasKey(skuId.toString());
            if (aBoolean) {
                //已存在 更新数据
                String json = hashOps.get(skuId.toString()).toString();
                cart = JsonUtils.parse(json, CartSon.class);
                //查询是否限制购买数量,是否超过购买限制数量
                if (cart.getLimitNum() == null || num + cart.getNum() <= cart.getLimitNum()) {
                    cart.setNum(cart.getNum() + num);
                }
                //保存原来的价格数据
                cart.setOldPrice(cart.getOldPrice());
            } else {
                cart.setUserId(user.getId());
            }
            hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
        }
        return true;
    }

    public void deleteCart(String uid, Long id) {
        String key = KEY_PREFIX + uid;
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        hashOps.delete(id.toString());
    }

}
